package transfos;

import java.io.File;

import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EPackage.Registry;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.emf.ecore.xmi.impl.XMIResourceFactoryImpl;
import org.eclipse.uml2.uml.Package;

import uml2Java.JavaChargeur;
import uml2Java.MultipleInheritanceNotAllowedException;
import uml2Java.TransformAssociations;
import uml2Java.TransformAttributes;
import uml2Java.TransformInheritance;
import uml2Java.TransformMethods;
import uml2Java.TransformPackagesAndTypes;
import astjava.Model;
import fr.irit.etracetool.etrace.ETrace;
import fr.irit.etracetool.etrace.EtracePackage;

public class Transfo {

	protected Model javaModel;
	protected Package umlPackage;
	protected String chemin;

	public static ETrace getEtrace(String location) {
		ResourceSet resourceSet = new ResourceSetImpl();
		registerPackages(resourceSet);
		Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap().put("xmi", new XMIResourceFactoryImpl());
		Resource resource = resourceSet.getResource(URI.createFileURI(new File(location).getAbsolutePath()), true);
		return (ETrace) resource.getContents().get(0);
	}

	public void transform() {
		TransformPackagesAndTypes t = new TransformPackagesAndTypes(umlPackage, javaModel);
		TransformAttributes ta = new TransformAttributes(t);
		TransformMethods tm = new TransformMethods(t);
		TransformInheritance ti = new TransformInheritance(t);
		TransformAssociations tas = new TransformAssociations(t);
		
		try {		
			t.doTransformPackagesAndTypes();
			ta.doTransformAttributes();
			tm.doTransformMethods();
			ti.doTransformInheritance();
			tas.doTransformAssociation();
		} catch (MultipleInheritanceNotAllowedException e) {
			e.printStackTrace();
		}
		
		JavaChargeur j = new JavaChargeur(chemin + ".astjava");
		j.save(javaModel);
	
	}

	protected static void registerPackages(ResourceSet resourceSet) {
			Registry packageRegistry = resourceSet.getPackageRegistry();
	//		packageRegistry.put(EcorePackage.eNS_URI, EcorePackage.eINSTANCE);
	//		packageRegistry.put(Ecore2XMLPackage.eNS_URI,Ecore2XMLPackage.eINSTANCE);
	//		packageRegistry.put(UMLPackage.eNS_URI, UMLPackage.eINSTANCE);
			packageRegistry.put(EtracePackage.eNS_URI, EtracePackage.eINSTANCE);
		}

	protected static void printTestResult() {
		ETrace trace = getEtrace("model/trace.xmi");
		System.out.println(trace.numberOfLinks());
		System.out.println(trace.numberOfCompositeLinks());
	}

	public Transfo() {
		super();
	}

}